package com.cssw.fyzb.busi.api.pay;

import com.alibaba.fastjson.JSON;
import com.cssw.fyzb.busi.config.TpsClient;
import com.cssw.fyzb.busi.model.tps.Tf56PayQuickSignQueryDataVo;
import com.cssw.fyzb.busi.model.tps.Tf56PayQuickSignQueryVo;
import com.cssw.fyzb.busi.service.pay.QuickPayService;
import com.cssw.fyzb.busi.util.MapUtil;
import com.cssw.fyzb.core.exception.BizException;
import com.cssw.fyzb.core.model.dodb.QuickNotifyLog;
import com.cssw.fyzb.core.model.dodb.QuickSignOrder;
import com.cssw.fyzb.core.model.dodb.UserQuickSign;
import com.cssw.fyzb.core.util.StringUtil;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplelock.SimpleLock;
import com.ydn.simplelock.SimpleLockFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author: yangyiqun
 * @Date: 2020/7/14 22:10
 */

@Function(description = "ada支付异步通知校验", parameters = {
        @Parameter(name = "params", type = Type.String, description = "参数", required = true),
})
@Component
public class QuickSignNotify implements Action {

    private static final Logger logger = LoggerFactory.getLogger(QuickSignNotify.class);
    @Autowired
    private TpsClient tpsClient;

    @Autowired
    private QuickPayService quickPayService;

    @Autowired
    private SimpleLockFactory simpleLockFactory;

    @Override
    public Response execute(Request request) throws Exception {
        String params = request.getString("params");
        try {
            logger.info(" params >>> " + params);

            Map param = JSON.parseObject(params, Map.class);
            String orderNo = MapUtil.getString(param, "businessnumber");
            String status = MapUtil.getString(param, "status");

            //记录回调日志
            QuickSignOrder quickSignOrder = quickPayService.getQuickSignOrderByOrderNo(orderNo);

            if (null == quickSignOrder) {
                saveQuickNotifyLog(0L, orderNo, "", status, params);
                return Response.fail("订单不存在");
            }

            if (!"成功".equals(status)) {
                quickPayService.updateQuickSignFail(quickSignOrder.getSignId(), "-1", status);
                saveQuickNotifyLog(quickSignOrder.getUserId(), orderNo, quickSignOrder.getBusiNo(), status, params);
                return Response.fail("签约失败");
            }
            Tf56PayQuickSignQueryVo vo = null;
            try {

                vo = orderQuery(orderNo);
                if (vo == null) {
                    quickPayService.updateQuickSignFail(quickSignOrder.getSignId(), "-1", "返回对象为空");
                    saveQuickNotifyLog(quickSignOrder.getUserId(), orderNo, quickSignOrder.getBusiNo(), "-1", "返回对象为空", params);
                    return Response.fail("返回对象为空");
                }
                Tf56PayQuickSignQueryDataVo dataVo = vo.getDataVo();

                if (null == dataVo) {
                    quickPayService.updateQuickSignFail(quickSignOrder.getSignId(), "-1", "返回业务对象为空");

                    saveQuickNotifyLog(quickSignOrder.getUserId(), orderNo, quickSignOrder.getBusiNo(), "-1", "返回业务对象为空", params);
                    return Response.fail("返回业务对象为空");
                }
                if (!"成功".equals(dataVo.getStatus())) {
                    quickPayService.updateQuickSignFail(quickSignOrder.getSignId(), "-1", "订单未成功");

                    saveQuickNotifyLog(quickSignOrder.getUserId(), orderNo, quickSignOrder.getBusiNo(), "-1", "订单未成功", params);
                    return Response.fail("订单未成功");
                }

            } catch (Exception e) {
                logger.error("", e);
                if (e instanceof BizException) {
                    BizException be = (BizException) e;
                    quickPayService.updateQuickSignFail(quickSignOrder.getSignId(), String.valueOf(be.getErrCode()), be.getErrMsg());

                    saveQuickNotifyLog(quickSignOrder.getUserId(), orderNo, quickSignOrder.getBusiNo(), String.valueOf(be.getErrCode()), be.getErrMsg(), params);
                    return Response.fail(be.getErrMsg(), be.getErrCode());
                }

                quickPayService.updateQuickSignFail(quickSignOrder.getSignId(), "-1", e.getMessage());

                saveQuickNotifyLog(quickSignOrder.getUserId(), orderNo, quickSignOrder.getBusiNo(), "-1", e.getMessage(), params);
                return Response.fail("校验订单失败");
            }

            SimpleLock simpleLock = simpleLockFactory.getLock("QUICKSIGN_" + orderNo);
            try {
                simpleLock.acquire();

                quickPayService.updateQuickSignSucc(quickSignOrder.getSignId());

                saveQuickNotifyLog(quickSignOrder.getUserId(), orderNo, quickSignOrder.getBusiNo(), status, params);
                String certCode = quickSignOrder.getCertCode();
                if (StringUtil.isEmpty(certCode)){
                    certCode =  MapUtil.getString(param, "certcode");
                }

                UserQuickSign userQuickSign = quickPayService.getUserQuickSignByUIdAndCardNo(quickSignOrder.getUserId(), quickSignOrder.getCardNo());
                if (null == userQuickSign) {
                    quickPayService.saveUserQuickSign(quickSignOrder.getUserId(), quickSignOrder.getCardNo(), quickSignOrder.getRealName(), quickSignOrder.getBankName(),
                            quickSignOrder.getBankCode(), certCode, quickSignOrder.getMobile(), quickSignOrder.getOrderNo(), quickSignOrder.getIdCard());
                }
            } finally {
                try{
                    simpleLock.release();
                } catch (Exception e){
                    logger.error("", e);
                }
            }
            logger.info(">>>QuickSignNotify:" + orderNo + ">>>" + vo);
        } catch (Exception e) {
            if (e instanceof BizException) {
                BizException be = (BizException) e;
                saveQuickNotifyLog(0L, "", "", String.valueOf(be.getErrCode()), be.getErrMsg(), params);
                return Response.fail(be.getErrMsg(), be.getErrCode());
            }

            logger.error("", e);
            saveQuickNotifyLog(0L, "", "", "", params);
            return Response.fail("操作失败");
        }
        return Response.success();
    }

    private void saveQuickNotifyLog(Long userId, String orderNo, String busiNo, String status, String param) {
        quickPayService.saveQuickNotifyLog(userId, orderNo, busiNo, QuickNotifyLog.TYPE_SIGN, "成功".equals(status) ? "0" : "-1", status, param);
    }

    private void saveQuickNotifyLog(Long userId, String orderNo, String busiNo, String errorCode, String errorMsg, String param) {
        quickPayService.saveQuickNotifyLog(userId, orderNo, busiNo, QuickNotifyLog.TYPE_SIGN, errorCode, errorMsg, param);
    }

    private Tf56PayQuickSignQueryVo orderQuery(String tradeNo) {
        Request request = new Request("Tf56PayQuickSignQuery");
        request.setParameter("orderNo", tradeNo);
        Response response = tpsClient.send(request);
        if (!response.isSuccess()) {
            throw new BizException(response.getCode(), response.getMessage());
        }
        return response.getData().get("data", Tf56PayQuickSignQueryVo.class);

    }
}